<template>
	<van-popup v-model:show="state.visible" closeable :style="{ width: '90%', height: '100%' }" position='right'
		@close="handleClose">
		<PDFRead v-if="state.fileType === 'PDF'" v-loading="state.loading" :src="state.src" :pageScale="pageScale"
			:height="state.height" :fileName="fileName"></PDFRead>
		<!-- <WordRead v-if="state.fileType==='WORD'" v-loading="state.loading" :src="state.src" :height="state.height"  :fileName="props.fileName" ></WordRead> -->
	</van-popup>
</template>
<script lang="ts">
	export default {
		name: "FileRead"
	}
</script>
<script setup lang="ts">
	import { reactive, watch } from "vue";
	import PDFRead from '@/components/FileRead/components/PDFRead.vue';
	import { downloadAttach, getFileAttachId, getUrlAttachId } from "@/utils/fileCommon";

	const state = reactive({
		visible: false,
		direction: 'rtl',
		height: '90vh',
		src: '' as any,
		loading: false,
		fileType: '',//文件类型
	})

	const props = defineProps({
		dialogVisible: {
			type: Boolean,
			default: false,
		},
		src: {
			type: String,
			default: ''
			//default:'http://erp.optosky.com:9001/test.pdf'
		},
		id:
			{
				type: String,
				default: ""
			},
		pageScale: {
			type: String,
			default: 'page-fit'
		}, // 默认自适应展示一页
		theme: {
			type: String,
			default: 'dark'
		},
		fileName: {
			type: String,
			default: '文件'
		},
	});
	const emits = defineEmits(['update:dialogVisible']);
	/**
	 * 关闭
	 */
	function handleClose() {
		state.visible = false;
		emits('update:dialogVisible', false)
	}

	/**
	 * 加载文件
	 * @param type pdf ,word
	 */
	async function loadFile(type : string) {
		if (!props.id) return;
		state.loading = true;
		let path = null;
		path = await getUrlAttachId(props.id) as string;
		/*if(type==='PDF')
		  path = await getUrlAttachId(props.id) as string;
		else
		  path= await getFileAttachId(props.id);*/
		if (path) {
			state.src = path
		}
		state.loading = false;
	}
	watch(
		() => props.dialogVisible,
		async (val) => {
			state.visible = val;
			if (val) {
				if (props.id) {
					if (props.fileName.toUpperCase().indexOf('.PDF') > -1) {
						state.fileType = 'PDF'
						await loadFile(state.fileType)
					}
					else if (props.fileName.toUpperCase().indexOf('.DOCX') > -1) {
						state.fileType = 'WORD'
						await loadFile(state.fileType)
					}
					else {
						emits('update:dialogVisible', false);
						downloadAttach(props.id, props.fileName)
					}
				}
				else {
					state.src = ''
					emits('update:dialogVisible', false);
					// ElMessage.info('未生成文件！')
				}
				if (props.src) {
					state.src = props.src;
				}
			}
		}
	);
</script>

<style scoped></style>